import React, { Component } from 'react'
import { connect } from 'dva'
import { Row, Col, Card, Form, Input, Button, TreeSelect, Select, DatePicker } from 'antd'
import { PageHeaderWrapper } from '@ant-design/pro-layout'
import styles from './Index.less'
import settings from '@/../config/defaultSettings'

const FormItem = Form.Item
const { TextArea } = Input
const { TreeNode } = TreeSelect
const { Option } = Select
const { RangePicker } = DatePicker

@connect(({ loading, propCheck, department, user, property }) => ({
  property,
  user,
  department,
  propCheck,
  loading: loading.models.propCheck,
}))
@Form.create()
export default class PropCUpdate extends Component {
  componentDidMount() {
    // const { currentItem } = this.props.propCheck
    const { dispatch } = this.props
    const propSelectKeys = ['property_status', 'property_class', 'location_seat']
    // 获取状态select数据
    // 资产分类select数据
    // 获取位置select数据
    propSelectKeys.forEach(key => {
      dispatch({
        type: 'property/fetchSelectPropData',
        payload: {
          type: key,
        },
      })
    })
    dispatch({
      type: 'department/listAll',
    })
  }

  handleSave() {
    const { dispatch } = this.props
    const { currentItem } = this.props.propCheck
    const { getFieldsValue, validateFields } = this.props.form

    validateFields(errors => {
      if (errors) {
        return
      }

      const data = {
        ...getFieldsValue(),
        id: currentItem.id,
      }

      delete data.pdOperator
      data.pdStartDate =
        data.rangeValue && data.rangeValue[0] ? data.rangeValue[0].format('YYYY-MM-DD') : undefined
      data.pdEndDate =
        data.rangeValue && data.rangeValue[1] ? data.rangeValue[1].format('YYYY-MM-DD') : undefined
      delete data.rangeValue
      data.scope = data.scope ? data.scope.join(',') : ''
      data.status = data.status ? data.status.join(',') : ''
      data.zcClass = data.zcClass ? data.zcClass.join(',') : ''
      data.zcSeat = data.zcSeat ? data.zcSeat.join(',') : ''

      // 编辑时 数据在model中初始化
      dispatch({
        type: 'propCheck/save',
        payload: data,
      })
    })
  }

  // 资产属性下拉option
  renderOptionNodes(type) {
    const data = this.props.property[type]
    return data.map(item => (
      <Option key={item.id} value={item.keyName}>
        {item.keyValue}
      </Option>
    ))
  }

  // 渲染部门树节点
  renderTreeNodes(data) {
    return data
      .map(item => {
        if (item.status === '0001') {
          if (item.children) {
            return (
              // 此处查询用 id
              <TreeNode title={item.name} key={item.id} value={item.id}>
                {this.renderTreeNodes(item.children)}
              </TreeNode>
            )
          }
          return <TreeNode title={item.name} key={item.id} value={item.id} />
        }
        return null
      })
      .filter(item => item || false)
  }

  // 简单搜索条件
  renderForm() {
    const { currentItem } = this.props.propCheck
    const { getFieldDecorator } = this.props.form
    const { allDepData } = this.props.department
    const { currentUser } = this.props.user

    return (
      <Form layout="inline">
        <div className={styles.fieldTitle}>基本信息</div>
        <Row gutter={{ md: 8, lg: 24, xl: 48 }}>
          <Col span={11} offset={1}>
            <FormItem label="盘点单名称">
              {getFieldDecorator('pdJobName', {
                initialValue: currentItem.pdJobName,
                whitespace: true,
                rules: [{ required: true, message: '不能为空' }],
              })(<Input placeholder="请输入" maxLength={settings.inputMaxLength} />)}
            </FormItem>
          </Col>
        </Row>
        <Row gutter={{ md: 8, lg: 24, xl: 48 }}>
          <Col span={11} offset={1}>
            <FormItem label="盘点范围">
              {getFieldDecorator('scope', {
                initialValue: currentItem.scope,
                whitespace: true,
                rules: [{ required: true, message: '不能为空' }],
              })(
                <TreeSelect
                  dropdownStyle={{ maxHeight: 400, overflow: 'auto' }}
                  showCheckedStrategy={TreeSelect.SHOW_ALL}
                  allowClear
                  showSearch
                  treeNodeFilterProp="title"
                  placeholder="请选择所属部门节点"
                  multiple
                >
                  {this.renderTreeNodes(allDepData)}
                </TreeSelect>,
              )}
            </FormItem>
          </Col>
          <Col span={11} offset={1}>
            <FormItem label="盘点负责人">
              {getFieldDecorator('pdOperator', {
                initialValue: currentUser.name,
              })(<Input placeholder="请输入" disabled />)}
            </FormItem>
          </Col>
        </Row>
        <Row gutter={{ md: 8, lg: 24, xl: 48 }}>
          <Col span={11} offset={1}>
            <FormItem label="资产分类">
              {getFieldDecorator('zcClass', {
                initialValue: currentItem.zcClass,
                whitespace: true,
                rules: [{ required: true, message: '不能为空' }],
              })(
                <Select mode="multiple" placeholder="请选择">
                  {this.renderOptionNodes('property_class')}
                </Select>,
              )}
            </FormItem>
          </Col>
          <Col span={11} offset={1}>
            <FormItem label="所在位置">
              {getFieldDecorator('zcSeat', {
                initialValue: currentItem.zcSeat,
                whitespace: true,
                rules: [{ required: true, message: '不能为空' }],
              })(
                <Select mode="multiple" placeholder="请选择">
                  {this.renderOptionNodes('location_seat')}
                </Select>,
              )}
            </FormItem>
          </Col>
        </Row>
        <Row gutter={{ md: 8, lg: 24, xl: 48 }}>
          <Col span={11} offset={1}>
            <FormItem label="状态">
              {getFieldDecorator('status', {
                initialValue: currentItem.status,
                whitespace: true,
                rules: [{ required: true, message: '不能为空' }],
              })(
                <Select mode="multiple" placeholder="请选择">
                  {this.renderOptionNodes('property_status')}
                </Select>,
              )}
            </FormItem>
          </Col>
          <Col span={11} offset={1}>
            <FormItem label="盘点时间">
              {getFieldDecorator('rangeValue', {
                initialValue: currentItem.rangeValue,
                whitespace: true,
                rules: [{ required: true, message: '不能为空' }],
              })(<RangePicker></RangePicker>)}
            </FormItem>
          </Col>
        </Row>
        <Row gutter={{ md: 8, lg: 24, xl: 48 }}>
          <Col span={23} offset={1}>
            <FormItem label="备注">
              {getFieldDecorator('remark', {
                initialValue: currentItem.remark,
              })(<TextArea placeholder="请输入" maxLength={settings.inputMaxLength} />)}
            </FormItem>
          </Col>
        </Row>
        <Button
          style={{ marginLeft: 135, marginTop: 10 }}
          type="primary"
          onClick={() => {
            this.handleSave()
          }}
        >
          保存提交
        </Button>
      </Form>
    )
  }

  // 渲染界面
  render() {
    return (
      <PageHeaderWrapper title="盘点单录入">
        <div className={styles.myContainer}>
          <Card className={styles.noPadding} bordered={false}>
            {this.renderForm()}
          </Card>
        </div>
      </PageHeaderWrapper>
    )
  }
}
